import React, {PureComponent, Fragment} from 'react';
import Ellipsis from './../../components/Ellipsis';
import {connect} from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Select,
  Button,
  Tag,
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Log.less';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['#2db7f5', '#f50'];
const status = ['正常', '异常'];

@connect(({log, loading}) => ({
  log,
  loading: loading.models.log,
}))
@Form.create()
export default class Log extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'log/fetch',
      payload: {
        orderByField: 'createTime',
        isAsc: false,
      }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    console.log(sorter)
    if (sorter.field) {
      params.orderByField = `${sorter.field}`
      if (sorter.order === 'ascend') {
        params.isAsc = true
      } else if (sorter.order === 'descend') {
        params.isAsc = false
      }
    }

    dispatch({
      type: 'log/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'log/fetch',
      payload: {},
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
       };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'log/fetch',
        payload: values,
      });
    });
  };

  render() {
    const {log: {data}, loading} = this.props;
    const {selectedRows} = this.state;
    const {getFieldDecorator} = this.props.form;
    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
        render: (val, record, index) => (data.pagination.current - 1) == 0 ? 1 + index : (data.pagination.current - 1) * data.pagination.pageSize + 1 + index
      },
      {
        title: '类型',
        dataIndex: 'type',
        render(val) {
          return <Tag color={statusMap[val > 0 ? 1 : 0]}>{status[val > 0 ? 1 : 0]}</Tag>
        },
      },
      {
        title: '请求接口',
        dataIndex: 'requestUri',
      },
      {
        title: 'IP地址',
        dataIndex: 'remoteAddr',
      },
      {
        title: '请求方式',
        dataIndex: 'method',
      },
      {
        title: '传入参数',
        dataIndex: 'params',
        render: val => <Ellipsis length={40} tooltip>{val}</Ellipsis>
      },
      {
        title: '请求时间',
        dataIndex: 'time',
        render: val => <span>{val}m</span>,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      }
    ];

    return (
      <PageHeaderLayout title="查看日志">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}><Form onSubmit={this.handleSearch} layout="inline">
              <Row gutter={{md: 8, lg: 24, xl: 48}}>
                <Col md={8} sm={24}>
                  <FormItem label="使用状态">
                    {getFieldDecorator('type')(
                      <Select placeholder="请选择" style={{width: '100%'}}>
                        <Option value="0">正常</Option>
                        <Option value="9">异常</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <span className={styles.submitButtons}>
                    <Button type="primary" htmlType="submit">
                      查询
                    </Button>
                    <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                      重置
                    </Button>
                  </span>
                </Col>
              </Row>
            </Form></div>

            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey="id"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
